﻿using AutoMapper;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;

namespace IOP.Extension.AutoMapper
{
    /// <summary>
    /// 自动映射扩展
    /// </summary>
    public static class AutoMapperExtensions
    {

        /// <summary>
        /// 添加自动化映射至服务
        /// </summary>
        /// <param name="service"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public static IServiceCollection AddAutoMapper(this IServiceCollection services, Assembly entry)
        {
            var entites = entry.GetTypes();
            return AddAutoMapperToServices(services, entites);
        }

        /// <summary>
        /// 添加自动化映射至服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddAutoMapper(this IServiceCollection services)
        {
            var entites = Assembly.GetEntryAssembly().GetTypes();
            return AddAutoMapperToServices(services, entites);
        }

        /// <summary>
        /// 添加映射服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        private static IServiceCollection AddAutoMapperToServices(IServiceCollection services, Type[] types)
        {
            services.AddSingleton<IMapper>(new Mapper(new MapperConfiguration(cfg =>
            {
                foreach (Type entity in types)
                {
                    if (entity.GetCustomAttributes(false).Any(x => x is AutoMappingAttribute))
                    {
                        AutoMappingAttribute auto = entity.GetCustomAttributes(false).Where(x => x is AutoMappingAttribute).First() as AutoMappingAttribute;
                        cfg.CreateMap(auto.SourceType, entity);
                        cfg.CreateMap(entity, auto.SourceType);
                    }
                }
            })));
            return services;
        }
    }
}
